-- ts_ocr_dict.lua - OCR字库工具模块
local logger = require "utils.logger"
local combat = require "modules.combat"
require "TSLib"

local OCRDict = {}
local ocrIndex = nil

-- 加载OCR字库数据
-- @param tab 字库数据数组
-- @return 字库索引
function OCRDict.loadDict(tab)
    if ocrIndex then
        logger.warn("OCR字库已加载，避免重复加载")
        return ocrIndex
    end
    ocrIndex = addTSOcrDictEx(tab)
    logger.info("OCR字库加载成功")
    return ocrIndex
end

-- 查找并点击文本
-- @param targetText 目标文本
-- @param x1,y1,x2,y2 查找区域坐标
-- @param colorParams 颜色参数
-- @param accuracy 匹配精度(0-100)
-- @param maxRetries 最大重试次数
-- @return found, x, y 是否找到及坐标
function OCRDict.findAndClickText(targetText, x1, y1, x2, y2, colorParams, accuracy, maxRetries)
    if not ocrIndex then
        logger.error("OCR字库未加载，请先调用loadDict")
        return false
    end

    maxRetries = maxRetries or 3
    local retry = 0
    local x, y

    while retry < maxRetries do
        x, y = tsFindText(ocrIndex, targetText, x1, y1, x2, y2, colorParams, accuracy)
        if x ~= -1 then
            logger.info(string.format("识别到目标文本 '%s'，坐标: %d,%d", targetText, x, y))
            tap(x, y)
            mSleep(500) -- 点击后延迟
            combat.startAutoAttack()
            return true, x, y
        else
            logger.info(string.format("未找到目标文本 '%s'，重试次数: %d", targetText, retry + 1))
            retry = retry + 1
            mSleep(1000)
        end
    end

    logger.error(string.format("达到最大重试次数，未找到目标文本 '%s'", targetText))
    return false
end

-- 查询虹魔教主
function OCRDict.findArcaneCaster()
    local tab = {
        "7ffc421842107ff03ff00200227e3efe2692e292629226923efe22ff0200000000000006100c1008101c101c1036d06270c2108213021e021c021802000200020000000006c01cc078c0f0c010c010c038c0ffff10c010c010c010c010c010c0000000000000001e7ff0540255f25df27d545d5cdff857fc555e5d567d5e5df654f64000000000000002410241024102410241027ffe7ffe4102410241024102410240020002$牛魔王$420$16$83",
        "0fc21fc218c6fffc18cc198c0f9e0002200220023ffe3ffe2002200220020000000000073ffc3e0002030cf23fb23d0ccfbccbfc4bfe0c0e3f0e3dfe0cfa0a0200000000044024d86d98ffbf6ffe3dd07c906f110f037f06f9fc107c19fc1f06180300000000000008020842084208420842c8c27ffe38c218420842084208420802$虹魔教主$385$16$65",
    }
    OCRDict.loadDict(tab)
    return OCRDict.findAndClickText("虹魔教主", 444, 63, 1213, 637, "CE0A0A , 3D0B0B", 90)
end

return OCRDict
